layui.define(['jquery', 'element'], function (exports) {
    "use strict";
    var $ = layui.$;
    var BMSTAB = function () {
    };
    var MOD_NAME = 'bmstab';
    var element = layui.element;
    element.on('tab(' + BMS.config.elems.boxTabFilter + ')', function (data) {
        BMS.cache.boxTabMenu.remove();// 移除右键弹出菜单
        // tab创建时 this 为标签外区
        // id
        BMS.cache.currentTab = BMS.cache.boxTab.find('li').eq(data.index);
        BMS.cache.currentTabCtx = BMS.cache.boxTabCtx.find('.layui-tab-item').eq(data.index).find('.layui-main');
        var id = BMS.cache.currentTab.attr('lay-id');
        call.tabLoad.call(this, data.index, id);
    });
    element.on('nav(' + BMS.config.elems.boxNavFilter + ')', function (data) {
        var aele = $(this).find('a');
        var title = aele.text().trim();
        var href = aele.attr(BMS.config.elems.boxTabNavDataHref);
        var navId = aele.attr(BMS.config.elems.boxTabNavDataId);

        call.tabAdd.call(this, title, href, navId);
    })

    // 基础事件体
    var call = {
        tabClear: function (index) {
            var elem = BMS.cache.currentTabCtx;
            elem.html('');
            BMS.cache.currentTab.attr(BMS.config.elems.boxTabLoadedFlag, 'false');
        },
        tabLoad: function (index, id) {
            // console.log("tabLoad index >> " + index + " id >> " + id);
            var $thisTab = BMS.cache.boxTab.find('li').eq(index);
            // 获取已加载标识
            var loaded = $thisTab.attr(BMS.config.elems.boxTabLoadedFlag);
            if ('true' == loaded && !BMS.config.setting.tabAutoRefresh)// 已加载，并且设置标签不自动刷新
                return;
            $thisTab.attr(BMS.config.elems.boxTabLoadedFlag, 'false');// 设置未加载

            // 获取 href
            var href = $thisTab.attr(BMS.config.elems.boxTabNavDataHref);
            if (!href) return;
            // ajax加载
            $.ajax({
                type: 'GET', url: href, success: function (resp) {
                    // 再判断一遍是否已加载，防止重复操作
                    loaded = $thisTab.attr('bms-loaded');
                    if ('true' == loaded)
                        return;
                    // 添加将响应内容
                    BMS.cache.currentTabCtx.html(resp);
                    $thisTab.attr(BMS.config.elems.boxTabLoadedFlag, 'true');// 设置已加载
                    // console.log('loaded >> ' + href);
                    element.init();
                }
            });
        },
        tabAdd: function (title, href, navId) {
            // todo 判断是否存在
            if (BMS.cache.boxTab.find('li[lay-id=' + navId + ']').length < 1) {
                var hrefName = BMS.config.elems.boxTabNavDataHref;
                var data={};
                data['title'] = title;
                data[hrefName] = href;
                data['id'] = navId;
                data['content'] = '<div class="layui-main"></div>';
                element.tabAdd(BMS.config.elems.boxTabFilter, data);
                bmstab.init();
            }
            element.tabChange(BMS.config.elems.boxTabFilter, navId);
        },
        tabRefresh: function (index, id) {
            // console.log("tabRefresh index >> " + index + " id >> " + id);
            // 先切换到标签
            element.tabChange(BMS.config.elems.boxTabFilter, id);
            // 再刷新
            call.tabClear(index);
            call.tabLoad(index, id);
        },
        tabCloseCurrent: function (index, id) {
            // console.log("tabCloseCurrent index >> " + index + " id >> " + id);
            // 定义lay-allowclose = false的不关闭
            if ('false' != BMS.cache.boxTab.find('li:eq(' + index + ')').attr('lay-allowclose')) {
                element.tabDelete(BMS.config.elems.boxTabFilter, id);
            }
        },
        tabCloseOther: function (index, id) {
            // console.log("tabCloseOther index >> " + index + " id >> " + id);
            layui.each(BMS.cache.boxTab.children('li'), function (cindex) {
                if (cindex == index) return;
                var cid = $(this).attr('lay-id');
                $.call(this, call.tabCloseCurrent(cindex, cid));
            })
        },
        tabCloseAll: function () {
            // console.log("tabCloseAll index");
            layui.each(BMS.cache.boxTab.children('li'), function (cindex) {
                var cid = $(this).attr('lay-id');
                $.call(this, call.tabCloseCurrent(cindex, cid));
            });
        },
        tabMenuClick: function (index, id) {
            var $this = $(this);
            //绑定菜单的点击事件
            $this.on('click', function () {
                //获取点击的target值
                var target = $this.data('target');
                //
                switch (target) {
                    case 'refresh': //刷新当前
                        call.tabRefresh(index, id);
                        break;
                    case 'closeCurrent': //关闭选中
                        call.tabCloseCurrent(index, id);
                        break;
                    case 'closeOther': //关闭其他
                        call.tabCloseOther(index, id);
                        break;
                    case 'closeAll': //全部关闭
                        call.tabCloseAll();
                        break;
                }
                //处理完后移除右键菜单的dom
                $(BMS.config.elems.boxTabMenuSelector).remove();
            });
        },
        tabRightClick: function (e) {
            e.preventDefault();
            e.stopPropagation();
            var $target = $(e.target.nodeName === 'LI' ? e.target : e.target.parentElement);
            //判断，如果存在右键菜单的div，则移除，保存页面上只存在一个
            $(document).find(BMS.config.elems.boxTabMenuSelector).remove();
            //创建一个div
            var div = document.createElement('div');
            //设置一些属性
            div.className = BMS.config.elems.boxTabMenuClass;
            div.style.width = '89px';
            div.style.backgroundColor = 'white';

            var ul = '<ul>';
            ul += '<li data-target="refresh" class="layui-btn layui-btn-primary layui-btn-small" style="width:89px;"><i class="layui-icon" style="color:#009688;">&#x1002;</i>刷&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;新</li>'
            ul += '<li data-target="closeCurrent" class="layui-btn layui-btn-primary layui-btn-small" style="width:89px;"><i class="layui-icon" style="color:#FF5722">&#x1006;</i>关&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;闭</li>'
            ul += '<li data-target="closeOther" class="layui-btn layui-btn-primary layui-btn-small"><i class="layui-icon">&#x1006;</i>关闭其他</li>'
            ul += '<li data-target="closeAll" class="layui-btn layui-btn-primary layui-btn-small"><i class="layui-icon">&#x1006;</i>关闭全部</li>'

            // 替换方式
            // var li = '<li data-target="#target#" class="layui-btn layui-btn-primary layui-btn-small"><i class="layui-icon">#logo#</i>#text#</li>';
            // ul += li.replace("#target#", 'refresh').replace("#logo#", "&#x1002;").replace("#text#", "刷新当前");
            // if ('false' == $target.attr('lay-allowclose'))//如果不允许关闭，则显示关闭按钮为disabled
            //     ul += li.replace('layui-btn', 'layui-btn layui-btn-disabled').replace("#target#", 'closeCurrent').replace("#logo#", "&#x1006;").replace("#text#", "关闭当前");
            // else
            //     ul += li.replace("#target#", 'closeCurrent').replace("#logo#", "&#x1006;").replace("#text#", "关闭当前");
            // 原
            // ul += li.replace("#target#", 'closeOther').replace("#logo#", "&#x1006;").replace("#text#", "关闭其他");
            // ul += li.replace("#target#", 'closeAll').replace("#logo#", "&#x1006;").replace("#text#", "关闭全部");
            // ul += '<li data-target="refresh" ><i class="fa fa-refresh" aria-hidden="true"></i> 刷新当前</li>';
            // ul += '<li data-target="closeCurrent" ><i class="fa fa-close" aria-hidden="true"></i> 关闭当前</li>';
            // ul += '<li data-target="closeOther" ><i class="fa fa-window-close-o" aria-hidden="true"></i> 关闭其他</li>';
            // ul += '<li data-target="closeAll" ><i class="fa fa-window-close-o" aria-hidden="true"></i> 全部关闭</li>';
            ul += '</ul>';
            div.innerHTML = ul;
            div.style.top = e.pageY + 'px';
            div.style.left = e.pageX + 'px';
            //将dom添加到body的末尾
            document.getElementsByTagName('body')[0].appendChild(div);
            BMS.cache.boxTabMenu = div;

            //获取当前点击选项卡的索引值
            var index = $target.index();
            //获取当前点击选项卡的id值
            var id = $target.attr('lay-id');
            var $context = $(document).find(BMS.config.elems.boxTabMenuSelector);
            if ($context.length > 0) {
                layui.each($context.eq(0).find('li'), function () {
                    call.tabMenuClick.call(this, index, id);
                });

                $(document).on('click', function () {
                    $context.remove();
                });
            }
            return false;
        }
    }
    //初始化元素操作
    BMSTAB.prototype.init = function () {
        var items = {
            contextMenu: function () {
                BMS.cache.boxTab.find('li').on('contextmenu', function (e) {
                    call.tabRightClick(e);
                });
            }
        };
        return layui.each(items, function (index, item) {
            item();
        });
    }


    var bmstab = new BMSTAB();
    bmstab.init();

    exports(MOD_NAME, bmstab);
});